import axios from 'axios'
import storage from 'store'
import store from '../store';
import {
	UniAdapter
} from 'uniapp-axios-adapter';
import {
	VueAxios
} from './axios'
import {
	login
} from '../api/user';
import {
	base_Url
} from './Url';
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';
// 创建 axios 实例
const request = axios.create({
	// API 请求的默认前缀
	baseURL: base_Url,
	timeout: 8000, // 请求超时时间
	adapter: UniAdapter

})

// 异常拦截处理器
const errorHandler = function(error) {
	// console.log('错误信息', error)
	const aa = uni.getStorageSync("code")
	if (aa) {
		uni.hideLoading();
		// console.log('用户错误信息', this);
	}

	if (error.response) {
		const data = error.response.data
		// 从 localstorage 获取 token
		const token = uni.getStorageSync('token')
		if (error.response.status === 403) {
			uni.showToast({

				title: data.message
			})
		}
		if (error.response.status === 401 && !(data.result && data.result.isLogin)) {

			uni.showToast({
				title: '权限失效或者无效',
				icon: "error"
			});
			if (token) {
				store.dispatch('Logout').then(() => {
					setTimeout(() => {
						// window.location.reload()
						uni.reLaunch({
							url: '/pages/login/login' // 页面路径
						});
					}, 1500)
				})
			} else {
				setTimeout(() => {
					// window.location.reload()
					uni.reLaunch({
						url: '/pages/login/login' // 页面路径
					});
				}, 1500)
			}
		}
	}
	return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use((config) => {
	const token = uni.getStorageSync("token")
	// console.log('token', token);
	// // 如果 token 存在
	// // 让每个请求携带自定义 token 请根据实际情况自行修改
	if (token) {
		config.headers['Access-Token'] = token
	}
	return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
	// console.log('响应的信息', response);
	return response.data
}, errorHandler)

const installer = {
	vm: {},
	install(Vue) {
		Vue.use(VueAxios, request)
	}
}

// 自定义适配器 ， 适配uniapp语法
request.defaults.adapter = function(config) {
	return new Promise((resolve, reject) => {
		let settle = require('axios/lib/core/settle');
		let buildURL = require('axios/lib/helpers/buildURL');
		let buildFullPath = require('axios/lib/core/buildFullPath');
		let fullurl = buildFullPath(config.baseURL, config.url);
		uni.request({
			method: config.method.toUpperCase(),
			url: buildURL(fullurl, config.params, config.paramsSerializer),
			header: config.headers,
			data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
			dataType: config.dataType,
			responseType: config.responseType,
			sslVerify: config.sslVerify,
			complete: function complete(response) {
				// console.log('uni.request 完整响应:', response);
				response = {
					data: response.data,
					status: response.statusCode,
					errMsg: response.errMsg,
					header: response.header,
					config: config
				};
				settle(resolve, reject, response);
			},
		});
	})
};




export default request

export {
	installer as VueAxios, request as axios
}